package cn.dlc.com.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * @author 邓立川
 * @date 2021/11/21 15:19
 * @desc 当前类的描述信息
 */
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
        // 内存里面创建了两个人
        userDetailsManager.createUser(User.withUsername("jack").password("{noop}123").authorities("p1").build());
        userDetailsManager.createUser(User.withUsername("rose").password("{noop}123").authorities("p2").build());
        return userDetailsManager;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 这部分访问需要权限
                .antMatchers("/user/r/r1").hasAnyAuthority("p1")
                .antMatchers("/user/r/r2").hasAnyAuthority("p2")
                // 这部分需要认证（非这部分的不需要认证）
                .antMatchers("/user/r/**").authenticated()
                // 其他请求不做限制
                .anyRequest().permitAll()
                // 配置登录相关的信息，登录成功之后跳转到login-success
                .and().formLogin().successForwardUrl("/user/login-success");
    }
}
